package com.xushi.service.impl;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

@Service
public class QRCodeGenerator {
    @Value("${littlefinger.qrcode.path}")
    String filePath;

    int width = 200; // 图像宽度
    int height = 200; // 图像高度

    String format = "png";// 图像类型

    public boolean encode(String fileName, String content) {
        try {
            Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
                    BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵
            Path path = FileSystems.getDefault().getPath(filePath, fileName);
            MatrixToImageWriter.writeToPath(bitMatrix, format, path);// 输出图像

            System.out.println("输出成功.");
        } catch (WriterException we) {
            System.out.println(we);
            return false;
        } catch (IOException ioe) {
            System.out.println(ioe);
            return false;
        }
        return true;
    }

    public byte[] getQRCode(String fileName) throws IOException {
        Path path = FileSystems.getDefault().getPath(filePath, fileName);
        if (Files.exists(path)) {
            byte[] data = Files.readAllBytes(path);
            return data;
        } else {
            return null;
        }
    }
}
